import React, { useCallback, useEffect, useState } from 'react';
import { Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import FormBox from './components/FormBox';
import TableBox from './components/TableBox';
import AddOrEdit from './components/AddOrEdit';
import columns from './components/TableBox/columns';
import {
  fetchUserList,
  fetchUserLock,
  fetchUserAdd,
  fetchUserUpdata,
} from '@/services/user';

import styles from './index.less';

const TablePage = () => {
  const [tableData, setTableData] = useState<any[]>([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });
  const [total, setTotal] = useState<number>(0);
  const [formSearch, setFormSearch] = useState<any>({});
  const [isVisibile, setIsVisibile] = useState<boolean>(false);
  const [flag, setFlag] = useState<string>('');
  const [userData, setUserData] = useState<any>({});
  const [userId, setUserId] = useState<number>(0);

  const getUserList = useCallback(async (body) => {
    try {
      const { data, meta } = await fetchUserList(body);
      setTableData(data);
      setTotal(meta.pagination.total);
    } catch (err) {
      console.log(err);
    }
  }, []);

  const handleChangePage = useCallback(
    ({ current }) => {
      getUserList({ current, ...formSearch });
      setPagination({ current, pageSize: 10 });
    },
    [formSearch],
  );

  const handleChangeChecked = useCallback(
    async (id) => {
      const res = await fetchUserLock(id);
      if (!res) {
        message.success('修改成功');
        getUserList({ current: 1 });
        setPagination({ current: 1, pageSize: 10 });
      }
    },
    [getUserList],
  );

  // 表单查询部分
  const handleFormSearch = useCallback(
    (values) => {
      setFormSearch(values);
      setPagination({ current: 1, pageSize: 10 });
      getUserList({ ...values, current: 1 });
    },
    [getUserList],
  );

  const handleReset = useCallback(async () => {
    await getUserList({ current: 1 });
    setPagination({ current: 1, pageSize: 10 });
    setFormSearch({});
  }, [getUserList]);

  // 编辑与新增
  const handleWrite = useCallback(() => {
    setFlag('add');
    setIsVisibile(true);
  }, []);

  const handleCancelWrite = useCallback(() => {
    setIsVisibile(false);
  }, []);

  const handleEdit = useCallback(async (record) => {
    setUserId(record.id);
    setUserData(record);
    setFlag('edit');
    setIsVisibile(true);
  }, []);

  const handleSubmit = useCallback(
    async (values) => {
      if (flag === 'add') {
        const res = await fetchUserAdd(values);
        if (!res) {
          getUserList({ current: 1 });
          setIsVisibile(false);
          message.success('添加成功');
          setFlag('');
        }
      } else if (flag === 'edit') {
        const res = await fetchUserUpdata(userId, values);
        if (!res) {
          getUserList({ current: 1 });
          setIsVisibile(false);
          message.success('编辑成功');
        }
      }
    },
    [flag, userId, getUserList],
  );

  const getColunms = useCallback(
    () => columns({ handleChangeChecked, handleEdit }),
    [columns, handleChangeChecked, handleEdit],
  );

  useEffect(() => {
    getUserList({ current: 1 });
  }, []);

  return (
    <>
      <FormBox onFormSearch={handleFormSearch} onReset={handleReset} />
      <div className={styles.pageTable}>
        <div className={styles.addBox}>
          <div>用户列表</div>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleWrite}>
            新增
          </Button>
        </div>
        <TableBox
          columns={getColunms()}
          data={tableData}
          pagination={pagination}
          total={total}
          onChangePage={handleChangePage}
        />
        <AddOrEdit
          isModalVisible={isVisibile}
          onCancelWrite={handleCancelWrite}
          flag={flag}
          onSubmit={handleSubmit}
          userData={userData}
        />
      </div>
    </>
  );
};

export default TablePage;
